import json
import time

import paho.mqtt.client as mqtt
from pydispatch import dispatcher

from logger import log
from settings import settings


class MQTTClient:
    def __init__(self):
        self.broker_address = settings.mqtt_server
        self.broker_port = 1883
        self.topic = f"weigh_node/{settings.code}/event/weight_data"
        # // {控制器产品型号}/{设备code}/event/json
        #     const topic: string = `edge-node/${config.code}/event/json`;
        self.temperature_topic = f"edge-node/{settings.code}/event/json"
        self.access_control_topic = f"access_control/{settings.code}/command"
        self.username = settings.mqtt_username
        self.password = settings.mqtt_password
        self.client_id = settings.code
        self.protocol = mqtt.MQTTv5

        # 创建MQTT客户端实例，并指定客户端ID和协议版本
        self.client = mqtt.Client(client_id=self.client_id, protocol=self.protocol)
        # 设置用户名和密码
        if self.username and self.password:
            self.client.username_pw_set(self.username, self.password)

        # 绑定回调函数
        self.client.on_connect = self.on_connect

    def on_message(self, client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        dispatcher.send("access_control", msg=msg.payload.decode())

    def on_connect(self, client, userdata, sp, flags, rc):
        if flags == 0:
            log.info("mqtt Connected successfully")
            client.subscribe(self.access_control_topic)
            client.on_message = self.on_message
        else:
            log.info(f"mqtt Connection failed with code {rc}")

    def connect(self):
        # 连接到MQTT代理
        self.client.connect(self.broker_address, self.broker_port, 60)

    def callback(self, weight, wen):
        log.info(f'{self.topic}|{weight}|{wen}')
        self.client.publish(self.topic, json.dumps({"weight": weight, "wen": wen}), retain=True)

    def temperature_callback(self, camera_name, location, temperature):
        log.info(f'{self.temperature_topic}|{temperature}')
        # const dataObj: any = {
        #         platformName: config.platformName,
        #         platformId: config.platformId,
        #         name: cameraName,
        #         data: {
        #             [`coal_temperature@${location}`]: temperature
        #         }
        #     };
        data_obj = {
            "platformName": settings.platformName,
            "platformId": settings.platformId,
            "name": camera_name,
            "data": {
                f"coal_temperature@{location}": temperature
            }
        }
        self.client.publish(self.temperature_topic, json.dumps(data_obj), retain=True)

    def start(self):
        self.connect()
        dispatcher.connect(self.callback, signal="weight")
        dispatcher.connect(self.temperature_callback, signal="temperature")
        # 启动客户端的循环处理线程
        self.client.loop_start()

    def stop(self):
        # 停止客户端的循环处理线程
        self.client.loop_stop()
        # 断开连接
        self.client.disconnect()


# 使用示例
if __name__ == "__main__":
    settings.code = "aaaa"

    mqtt_client = MQTTClient()
    mqtt_client.start()
    while True:
        # dispatcher.send("event", key="radar_state", event="online")
        dispatcher.send("weight", weight=1, wen=False)
        time.sleep(500)
